#include "http.hpp"

#define WWWROOT "./wwwroot/"

std::string RequestStr(const HttpRequest &req) {
    std::stringstream ss;
    ss << req._method << " " << req._path << " " << req._version << "\r\n";
    for (auto &it : req._params) {
        ss << it.first << ": " << it.second << "\r\n";
    }
    for (auto &it : req._headers) {
        ss << it.first << ": " << it.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;
    return ss.str();
}
void Hello(const HttpRequest &req, HttpResponse *rsp) 
{
    std::cout << "hello函数被调用，请求体：" << req._body << std::endl; // 新增日志
    rsp->SetContent(RequestStr(req), "text/plain");
    // sleep(15);测试4用的
}
void Login(const HttpRequest &req, HttpResponse *rsp) 
{
    std::cout << "Login函数被调用，请求体：" << req._body << std::endl; // 新增日志
    rsp->SetContent(RequestStr(req), "text/plain");
}
// void Login(const HttpRequest &req, HttpResponse *rsp) {
//     // 从解析后的_params中获取表单数据
//     std::string user = req.GetParam("username");
//     std::string pass = req.GetParam("password");

//     // 构造HTML响应，展示登录信息
//     std::string body;
//     body += "<html><head><meta charset='utf8'></head><body>";
//     body += "<h1>登录成功</h1>";
//     body += "用户名: " + user + "<br>";
//     body += "密码: " + pass + "<br>";
//     body += "</body></html>";

//     // 设置响应格式（必须指定text/html，否则客户端可能当作文本处理）
//     rsp->SetContent(body, "text/html; charset=utf-8");
// }
void PutFile(const HttpRequest &req, HttpResponse *rsp) 
{
    std::string pathname = WWWROOT + req._path;
    Util::WtiteFile(pathname, req._body);
}
void DelFile(const HttpRequest &req, HttpResponse *rsp) 
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
int main()
{
    Httpserver server(9999);
    server.SetThreadCount(3);
    server.SetBaseDir(WWWROOT);//设置静态资源根目录，告诉服务器有静态资源请求到来，需要到哪里去找资源文件
    server.Get("/hello", Hello);
    server.Post("/login", Login);
    server.Put("/1234.txt", PutFile);
    server.Delete("/1234.txt", DelFile);
    server.Listen();
    return 0;
}